﻿/*
 * Project Source: https://fakexrmpage.codeplex.com
 * Authors: Patrick Verbeeten
 * Version: 1.0
 * Date: 2014-06-25
 */

/* *****************************************************************************
Copyright (c) Patrick Verbeeten (PatrickVerbeeten.com). All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */


/** Root object of the Xrm model. This is available within the context forms (i.e. custom script in a form) */
declare var Xrm: XrmTypes.Xrm;
declare var ExecutionObj: XrmTypes.ExecutionContext;
/** Method to obtain a reference to the Xrm Context object when executing from a webresource */
declare var GetGlobalContext: XrmTypes.GetGlobalContext;

declare module XrmTypes {
    export interface GetGlobalContext {
        (): Context;
    }

    /** Genric function call used by various collection method in the Xrm Page model 
     * T: Type of the item to be returned
     * R: Return type (typeically boolean or void)
     */
    export interface XrmFunctionCallback<T, R> {
        (item: T, index?: number): R;
    }
    /** Generic event interface for OnChange en OnSave events */
    export interface XrmEvent {
        (source?: ExecutionContext)
    }

    /** Generic base collection for all items collections used by the Xrm Page model
    * T: Type of the item in the collection
    */
    export interface ControlsCollection<T> {
        /** Applies the action contained within a delegate function.   
         * @param {delegate} delegate - Method to execute
         */
        forEach(delegate: XrmFunctionCallback<T, void>): void;
        /** Returns all items */
        get(): T[];
        /** Returns the item by name
         * @param {string} name Name of the element to get
         */
        get(name: string): T;
        /** Returns the item by name
         * @param {Number} index Index of the element to get
         */
        get(index: number): T;
        /** Returns all items matching the criteria in the delegate
         * @param {delegate} delegate Method used to filter the collection
         */
        get(delegate: XrmFunctionCallback<T, boolean>): T[];
        /** Returns the number of items in the collection */
        getLength(): number;
    }

    export interface Xrm {
        /** Xrm Page for access to the current page */
        Page: Page;
        /** Utility function (Available from UR12 and up) */
        Utility: Utility;
    }

    export interface Utility {
        /** Opens an entity form.
         * @param {string} name Logical name of the entity
         * @param {string} id Id of the record to open. If this is not specified a new record is created.
         * @param {object} parameters Optional dictionary containing additional params (such as formid and default values)
         */
        openEntityForm(name: string, id?: string, parameters?: Object): Object;
        /** Opens an HTML web resource in a new window
        * @param {string} webResourceName The name of the HTML web resource to open.
        * @param {string} webResourceData Optional value for the data querystring parameter
        * @param {number} width The width of the window to open in pixels.
        * @param {number} height The height of the window to open in pixels.
        */
        openWebResource(webResourceName: string, webResourceData?: string, width?: number, height?: number): Window; //Opens an HTML web resource.
        /** Displays a dialog box containing an application-defined message
         *  @remark This method is only available for Updated Entities.
         *  @param {string} message The text of the message to display in the dialog.
         *  @param {delegate} onCloseCallback A function to execute when the OK button is clicked.
         */
        alertDialog(message: string, onCloseCallback?: { (): void }): void;
        /** Displays a confirmation dialog box that contains an optional message as well as OK and Cancel buttons.
        *  @remark This method is only available for Updated Entities.
        *  @param {string} message The text of the message to display in the dialog.
        *  @param {delegate} yesCloseCallback A function to execute when the OK button is clicked.
        *  @param {delegate} noCloseCallback A function to execute when the Cancel button is clicked.
        */
        confirmDialog(message: string, yesCloseCallback: { (): void }, noCloseCallback: { (): void }): void;
    }

    export interface Page {
        /** The context object provides methods to retrieve information specific to an organization, a user, or parameters passed to a page */
        context: Context;
        /** provides methods to work with the form */
        data: data;
        /** The control object provides methods to change the presentation or behavior of a control and identify the corresponding attribute*/
        ui: ui;

        /** Returns all attributes */
        getAttribute(): Array<Attribute>;
        /** Returns the attribute which matches the name argument 
         * @param {string} name - Name of the attribute
         */
        getAttribute(name: string): Attribute;
        /** Returns the attribute by index
         * @param {number} index - Index of the attribute
         */
        getAttribute(index: number): Attribute;
        /** Returns an array of attributes filtered using the provided method 
         * @param {delegate} delegate - Function used to filter the result
         */
        getAttribute(delegate: XrmFunctionCallback<Attribute, boolean>): Array<Attribute>;

        /** Returns all controls */
        getControl(): Array<Control>;
        /** Returns the control which matches the name argument 
          * @param {string} name - Name of the control
          */
        getControl(nae: string): Control;
        /** Returns the control by index
          * @param {index} index - Index of the control
          */
        getControl(argument: number): Control;
        /** Returns an array of controls filtered using the provided method 
        * @param {delegate} delegate - Function used to filter the result
        */
        getControl(delegate: XrmFunctionCallback<Control, boolean>): Array<Control>;
    }

    export interface ui {
        /** Close the form */
        close(): void;
        /** Returns the currently focused control */
        getCurrentControl(): Control;
        /** Returns the form Type 
         * 0: Undefined
         * 1: Create
         * 2: Update
         * 3: Read Only
         * 4: Disabled
         * 5: Quick Create (Deprecated)
         * 6: Bulk Edit 
         */
        getFormType(): number;
        /** Returns the height of the viewport in pixels. */
        getViewPortHeight(): number;
        /** Returns the width of the viewport in pixels. */
        getViewPortWidth(): number;
        /** Causes the ribbon to re-evaluate data that controls what is displayed in it. */
        refreshRibbon(): void;
        /** A collection of all the controls on the page */
        controls: ControlsCollection<Control>;
        /** A collection of all the navigation items on the page */
        navigation: Navigation;
        /** A collection containing information about all the forms available for the user. */
        formSelector: FormSelector;
        /** A collection of all the tabs on the page. */
        tabs: ControlsCollection<Tab>;
    }

    /** Xrm.Page.data provides an entity object that provides collections and methods to manage data within the entity form. */
    export interface data {
        /** provides collections and methods to manage data within the entity form.*/
        entity: Entity;
    }

    /** provides collections and methods to manage data within the entity form.*/
    export interface Entity {
        /** The Xrm.Page.data.entity.attributes collection provides methods to access the data for a record displayed on the form */
        attributes: ControlsCollection<Attribute>;
        /** Sets a function to be called when the record is saved.    
         * @param {delegate} ev Add en event to on save
         */
        addOnSave(ev: XrmEvent): void;
        /** Returns a string representing the xml that will be sent to the server when the record is saved. */
        getDataXml(): string;
        /** Returns a string representing the logical name of the entity for the record. */
        getEntityName(): string;
        /** Returns a string representing the GUID id value for the record.*/
        getId(): string;
        /** Returns a Boolean value that indicates if any fields in the form have been modified. */
        getIsDirty(): boolean;
        /** Removes a function from the OnSave event hander.*/
        removeOnSave(ev: XrmEvent): void;
        /** Saves the record. This method has three possible parameters.
         * @param {string} param Determines the save method. This value can be null (or not specified), 'saveandclose' or 'saveandnew'
         */
        save(param?: string): void;
    }

    export interface FormSelector {
        items: ControlsCollection<FormSelectorItem>;
        getCurrentItem(): FormSelectorItem; // Returns a reference to the form currently being shown.
    }

    export interface Context {
        /** Deprecated. Returns the encoded SOAP header necessary to use Microsoft Dynamics CRM web service calls using JScript. */
        getAuthenticationHeader(): string;
        /** Returns a string representing the current Microsoft Office Outlook theme chosen by the user.*/
        getCurrentTheme(): string;
        /** Returns the LCID value that represents the Microsoft Dynamics CRM Language Pack that is the base language for the organization. */
        getOrgLcid(): number;
        /** Returns the unique text value of the organizations name.*/
        getOrgUniqueName(): string;
        /** Returns an array of key value pairs representing the query string arguments that were passed to the page.*/
        getQueryStringParameters(): string[];
        /** DEPRECATED after RU 12 Returns the base server URL. When a user is working offline with Microsoft Dynamics CRM for Microsoft Office Outlook, the URL is to the local Microsoft Dynamics CRM Web services.*/
        getServerUrl(): string;
        /** Returns the base URL that was used to access the application This method is new in Microsoft Dynamics CRM 2011 Update Rollup 12 and the Microsoft Dynamics CRM December 2012 Service Update*/
        getClientUrl(): string;
        /** Returns the GUID value of the SystemUser.id value for the current user. */
        getUserId(): string;
        /** Returns the LCID value that represents the Microsoft Dynamics CRM Language Pack that is the user selected as their preferred language. */
        getUserLcid(): number;
        /** Returns an array of strings representing the GUID values of each of the security roles that the user is associated with. */
        getUserRoles(): string[];
        /** Returns a Boolean value indicating if the user is using Microsoft Dynamics CRM for Microsoft Office Outlook.*/
        isOutlookClient(): boolean;
        /** Returns a Boolean value indicating whether the user is connected to the Microsoft Dynamics CRM server while using Microsoft Dynamics CRM for Microsoft Office Outlook with Offline Access. When this function returns false, the user is not connected to the server. The user is interacting with an instance of Microsoft Dynamics CRM running on the local computer.*/
        isOutlookOnline(): boolean;
        /** Prepends the organization name to the specified path.
         * @param {string} sPath A local path to a resource.
         */
        prependOrgName(sPath: string): string;
    }

    /** navigation items on the page */
    export interface Navigation {
        /** navigation items on the page */
        items: ControlsCollection<NavigationItem>;
    }
    export interface FormSelectorItem {
        /** Returns the GUID ID of the roleForm.
        */
        getId(): string;
        /** Returns the label of the roleForm.
         * 
         */
        getLabel(): string;
        /** Opens the specified roleForm.
         * 
         */
        navigate(): void;
    }

    export interface Tab {
        /** Returns a value that indicates whether the tab is collapsed or expanded.
         * Possible values: expanded, collapsed
         */
        getDisplayState(): string;
        /* Returns the tab label */
        getLabel(): string;
        /* Returns the Xrm.Page.ui (client-side reference) object. */
        getParent(): ui
        /** Returns the name of the tab */
        getName(): string;
        /* Returns a value that indicates whether the tab is visible. */
        getVisible(): boolean;
        /** Sets the tab to be collapsed or expanded.
         * @param {string} value One of the following: expanded, collapsed
         */
        setDisplayState(value: string): void;
        /** Sets the focus on the tab */
        setFocus(): void;
        /** Sets the tab label */
        setLabel(value: string): void;
        /* Sets a value that indicates whether the control is visible */
        setVisible(value: boolean): void;
        /* The sections collection provides access to sections within the tab */
        sections: ControlsCollection<Section>;
    }
    export interface Section {
        /** Returns the label for the section */
        getLabel(): string;
        /** Method to return the name of the section */
        getName(): string;
        /** Method to return the tab containing the section */
        getParent(): Tab;
        /** Returns true if the section is visible, otherwise returns false. */
        getVisible(): boolean;
        /** Sets the label for the section */
        setLabel(value: string): void;
        /** Sets a value to show or hide the section */
        setVisible(value: boolean): void;
        /** The section controls collection provides access to the controls within a section. */
        controls: ControlsCollection<Control>;

    }
    /** The control object provides methods to change the presentation of a control and identify the corresponding attribute (if applicable. */
    export interface Control {
        /** Adds a new view for the lookup dialog. 
         * @param {string} viewId The string representation of a GUID for a view. This value is never saved and only needs to be unique among the other available views for the lookup.
         * @param {string} entityName Name of the entity
         * @param {string} viewDisplayName Name of the view
         * @param {string} fetchXml The fetchXml query for the view.
         * @param {string} layoutXml The XML that defines the layout of the view.
         * @param {boolean} isDefault Whether the view should be the default view.
         */
        addCustomView(viewId: string, entityName: string, viewDisplayName: string, fetchXml: string, layoutXml: string, isDefault: boolean): void;
        /** Adds an option to an Option set control.
         * @param {Option} option to add
         * @param {number} index (Optional) The index position to place the new option. If not provided the option will be added to the end.
         */
        addOption(option: Option, index?: number): void;
        /** Clears all options from an Option Set control */
        clearOptions(): void;
        /** Returns the attribute that the control is bound to.
         * Controls that are not bound to an attribute do not have this method. They will return error number -2146823281 with the error message: “'getAttribute()' is null or not an object”.
         */
        getAttribute(): Attribute;
        /** Returns a value that categorizes controls
         * Possible values: standard, iframe, lookup, optionset, subgrid, webresource
         */
        getControlType(): string;
        /** Returns the value of the data query string parameter passed to a Silverlight Web resource. */
        getData(): string;
        /** Returns the ID value of the default lookup dialog view.*/
        getDefaultView(): string;
        /** Returns a value that indicates whether the control is disabled.*/
        getDisabled(): boolean;
        /** Returns the label for the control */
        getLabel(): string;
        /** Returns the name assigned to the control */
        getName(): string;
        /** Returns a reference to the section object that contains the control. */
        getParent(): Section;
        /** Returns the current URL being displayed in an IFRAME*/
        getSrc(): string;
        /** Returns the default URL that an IFrame control is configured to display*/
        getInitialUrl(): string;
        /** Returns the object in the form representing an IFrame or Web resource.
         * An I-frame will return the IFrame element from the Document Object Model (DOM).
         * A Web resource will return the Object element from the DOM that represents the embedded Silverlight plug-in.
         */
        getObject(): Object;
        /** Returns a value that indicates whether the control is currently visible*/
        getVisible(): boolean;
        /** Refreshes the data displayed in a Sub-Grid*/
        refresh(): void;
        /** Removes an option from an Option Set control.
         * @param {number} value Value of the option to remove
         */
        removeOption(value: number): void;
        /** Sets the value of the data query string parameter passed to a Silverlight Web resource. */
        setData(value: string): void;
        /** Sets the default view for the lookup control dialog.*/
        setDefaultView(viewGuid: string): void;
        /** Sets a value that indicates whether the control is disabled.*/
        setDisabled(value: boolean): void;
        /** Sets the focus on the control*/
        setFocus(): void;
        /** Sets the label for the control.*/
        setLabel(label: string): void;
        /** Sets the URL to be displayed in an IFrame. */
        setSrc(value: string): void;
        /** Sets a value that indicates whether the control is visible. */
        setVisible(value: boolean): void;
    }
    export interface Attribute {
        /** Add an onchange event handler
         * @param {delegate} ev Method to execute on change
         */
        addOnChange(ev: XrmEvent): void;
        /** Causes the OnChange event to occur on the attribute so that any script associated to that event can execute. */
        fireOnChange(): void;
        /** Returns a string value that represents the type of attribute.
         * This method will return one of the following string values: boolean, datetime, decimal, double, integer, lookup, memo, money, optionset, string
         */
        getAttributeType(): string;
        /** Returns a string value that represents formatting options for the attribute.
        * Posible Vlaue: null, date, datetime, duration, email, language, none, text, tickersymbol, timezone, url
        */
        getFormat(): string;
        /** Returns a value that represents the value set for an optionset or Boolean attribute when the form opened.
        * Only valid for attributes of type boolean and optionset
        */
        getInitialValue(): number;
        /** Returns a Boolean value indicating if there are unsaved changes to the attribute value. */
        getIsDirty(): boolean;
        /** Returns a number indicating the maximum allowed value for an attribute.
        * Attribute Types: money, decimal, integer, double 
        */
        getMax(): number;
        /** Returns a number indicating the maximum length of a string or memo attribute.
        * Attribute Types: string, memo
        */
        getMaxLength(): number;
        /** Returns a number indicating the minimum allowed value for an attribute.
        * Attribute Types: money, decimal, integer, double 
        */
        getMin(): number;
        /** Returns a string representing the logical name of the attribute */
        getName(): string;
        /** Returns an option object with the value matching the argument passed to the method.
         * Attribute Types: optionset 
         * @param {number} value Value of the option to retrieve (as specified in the metadata)
         */
        getOption(value: number): Option;
        /** Returns an option object with the value matching the argument passed to the method. 
         * Attribute Types: optionset 
         * @param {string} value TBD
         */
        getOption(value: string): Option;
        /** Returns an array of option objects representing the valid options for an optionset attribute.
         * Attribute Types: optionset 
         */
        getOptions(): Array<Option>;
        /** Returns the entity object that is the parent to the attribute. */
        getParent(): Entity;
        /** Returns the number of digits allowed to the right of the decimal point.
        * Attribute Types: money, decimal, double, and integer
        */
        getPrecision(): number;
        /** Returns a string value indicating whether a value for the attribute is required or recommended. */
        getRequiredLevel(): string;
        /** Returns the option object that is selected in an optionset attribute.
         * Attribute Types: optionset
         */
        getSelectedOption(): Option;
        /** Returns a string indicating when data from the attribute will be submitted when the record is saved.
         * Possible value: always, never, dirty
          */
        getSubmitMode(): string;
        /** Returns a string value of the text for the currently selected option for an optionset attribute.
         * Attribute Types: optionset
        */
        getText(): string;
        /** Returns an object with three boolean properties corresponding to privileges indicating if the user can create, read or update data values for an attribute. This function is intended for use when Field Level Security modifies a user’s privileges for a particular attribute. */
        getUserPrivilege(): UserPrivilege;
        /** Retrieves the data value for an attribute. */
        getValue(): any;
        /** Removes a function from the OnChange event hander for an attribute
         * @param {delegate} ev Function reference to remove
         */
        removeOnChange(ev: XrmEvent): void;
        /** Sets whether data is required or recommended for the attribute before the record can be saved.
        * @param {string} requirementLevel One of the following values: none, required, recommended
        */
        setRequiredLevel(requirementLevel: string): void;
        /** Sets whether data from the attribute will be submitted when the record is saved.
         * @param {string} submitMode One of the following values: always, never, dirty */
        setSubmitMode(submitMode: string): void;
        /** Sets the data value for an attribute. 
         * @param {any} value
         */
        setValue(value: any);
    }
    export interface NavigationItem {
        /** Returns the id of the item. */
        getId(): string;
        /** Returns the label for the item*/
        getLabel(): string;
        /** Returns a value that indicates whether the item is currently visible. */
        getVisible(): boolean;
        /** Sets the focus on the item */
        setFocus(): void;
        /** Sets the label for the item
         * @param {boolean} label Label
         */
        setLabel(label: string): void;
        /** Sets a value that indicates whether the item is visible 
         * @param {boolean} value Visible
         */
        setVisible(value: boolean): void;
    }

    /** Contains permissions for the current user */
    export interface UserPrivilege {
        /** Is the user allowed to vread the value */
        canRead: boolean;
        /** Is the user allowed to update the value */
        canUpdate: boolean;
        /** Is the user allowed to provide a value when create */
        canCreate: boolean;
    }
    export interface LookupItem {
        Name: string;
        Id: string;
        EntityType: string;
    }
    export interface Option {
        text: string;
        value: string;
    }

    export interface ExecutionContext {
        /**  Returns the Xrm.Page.context object.*/
        getContext(): Context;
        /** Returns a value that indicates the order in which this handler is executed. */
        getDepth(): number;
        /** Returns an object with methods to manage the Save event.*/
        getEventArgs(): SaveEventArgs;
        /** Returns a reference to the object that the event occurred on.*/
        getEventSource(): Attribute;
        /** Retrieves a variable set using setSharedVariable*/
        getSharedVariable(key: string): Object;
        /** Sets the value of a variable to be used by a handler after the current handler completes*/
        setSharedVariable(key: string, value: Object);
    }
    export interface SaveEventArgs {
        /** Returns a value indicating how the save event was initiated by the user
         * 1: Save
         * 2: Save and Close
         * 5: Deactivate
         * 6: Reactivate
         * 7: Send (email)
         * 15: Disqualify (lead)
         * 16: Qualify (lead)
         * 47: Assign
         * 58: Save as Completed (activities)
         * 59: Save and New
         */
        getSaveMode(): number;
        /** Returns a value indicating whether the save event has been canceled because the preventDefault method was used in this event handler or a previous event handler. */
        isDefaultPrevented(): boolean; //   
        /** Cancels the save operation, but all remaining handlers for the event will still be executed. */
        preventDefault(): void;
    }

}